import json
import urllib
import datetime
import math
from django.shortcuts import render
from django.db.models import Q
from django.http import HttpResponse, HttpResponseNotFound, JsonResponse
from microerp.apps.salesorder.models import *
from microerp.apps.product.models import Product
from microerp.apps.base.views import islogin, get_user_id


def new_so(request):
    return render(request, 'so/new-so.html')

'''
获得销售订单记录
'''


def so_list(request):
    if islogin(request):
        user = Users.objects.filter(id=get_user_id(request))[0]
        # query-----查询关键字
        # page------页码（每页10条数据）
        query = request.GET.get('query', '')
        page = request.GET.get('page', 1)
        # 得到顾客列表数据
        so_list, totalRecords = get_salesorders(query, user, int(page))
        # 开始获得分页数据
        totalPage = math.ceil(totalRecords / 10)
        return render(request, 'so/so-list.html', {'list': so_list, 'query': query, "totalPage": totalPage, "totalRecords": totalRecords})
    else:
        return render(request, 'base/signin.html')


def analysis(request):
    return render(request, 'so/analysis.html')


'''
获取订单详细信息
参数：num:订单编号
返回：数据渲染页面
'''


def so_detail(request):
    if islogin(request):
        user = Users.objects.filter(id=get_user_id(request))[0]
        so_num = request.GET.get('num', '')
        so = SalesOrder.objects.filter(so_num=so_num)
        if len(so) is not 0:
            sl = SalesLine.objects.filter(sl_so=so)
            return render(request, 'so/so-detail.html', {'so': so[0], 'sl': sl})
        else:
            return HttpResponseNotFound()
    else:
        return render(request, 'base/signin.html')


'''
添加销售订单的接口
###得到传来的JSON字符串数据并加以解析
###创建销售订单对象已经销售行数组
###存储到数据库
'''


def api_add_so(request):
    if islogin(request):
        user = Users.objects.filter(id=get_user_id(request))[0]
        str_req = request.body.decode()
        line_list = []  # for save orderlines
        so_dict = json.loads(str_req)  # transform json data to dict
        print(so_dict)
        # create a new salesorder
        so = SalesOrder(
            user=user,
            so_cust=Customer.objects.filter(
                user=user).filter(account_name=so_dict["cust"])[0],
            so_creattime=so_dict['date'],
            so_address=so_dict['address'],
            so_note=str(so_dict['note']),
        )
        so.convert_No()
        so.save()  # save salesorde in database
        '''
        Get order lines from post data and append them in new list(SalesLine)
        '''
        lines = so_dict['orderlines']
        for item in lines:
            product = Product.objects.filter(
                user=user).filter(name=item['name'])[0]
            salesLine = SalesLine(
                sl_prod=product,
                sl_quantity=item['quantity'],
                sl_price=item['price']
            )
            # 对应product的库存被减去
            product.inventory = product.inventory - salesLine.sl_quantity
            product.save()
            line_list.append(salesLine)

        # after get data of lines. we should save them to database.
        for line in line_list:
            line.sl_so = so
            line.save()
        return JsonResponse({'statu': 'OK'})
    else:
        return render(request, 'base/signin.html')


'''
### 分页获取SalesOrder的json数据
### 传入参数：
### obj：查询参数
### user：用户
### page：页码
'''


def get_salesorders(obj, user, page):
    so_list = []  # 新建一个list存储销售订单列表
    totalRecords = 0  # 总记录数量
    if len(obj) is not 0:
        so_list = SalesOrder.objects.filter(
            user=user).filter(
            Q(so_num__icontains=str(obj)) | Q(
                so_cust__name__icontains=str(obj))
        ).order_by("id")[(page - 1) * 10:page * 10 - 1]
        totalRecords = SalesOrder.objects.filter(
            user=user).filter(name__icontains=str(obj)).count()
    else:
        so_list = SalesOrder.objects.filter(user=user).order_by(
            "-id")[(page - 1) * 10:page * 10]
        totalRecords = SalesOrder.objects.filter(user=user).count()
    return so_list, totalRecords
